<template>
	<view>
		<j-header ref="jheader" navigate="device" :isShowRight="false" @loadhandler="onLoadHandler"></j-header>
		<view class="tips">
			请关注<text style="color:#FF0025;" @click="copyText()">“小峰管家”</text>微信公众号并开通消息提醒才会收到设备推送消息哦！
		</view>
		<!-- <view style="margin-top: 20rpx;">
			<official-account></official-account>
		</view> -->
		<view class="">
			<j-cell-group>
				<j-cell v-for="(item,index) in deviceList" :key="index" :title="item.deviceName" :more="false">
					<view slot="icon">
						<image :src="item.devicePic" style="width: 40rpx;height: 40rpx;margin-left: 20rpx;"></image>
					</view>
					<view slot="tips">
						<!-- <switch :checked="item.isSubscribe" color="#FF0025" style="transform:scale(0.8)"
							@change="switchChange(item,$event)"></switch> -->
						<j-switch :disabled="disabled" v-model="item.isSubscribe" color="#FF0025" @change="switchChange(item,$event)" ></j-switch>
					</view>
				</j-cell>
			</j-cell-group>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				deviceList: [], // 设备列表
				isSubscribe:false,
				isAuth:true,
				disabled:false,
			};
		},
		onShow: function() {
			wx.getSetting({
				withSubscriptions: true,
				success (res) {
				  console.log('authSetting========',res)
				  // res.authSetting = {
				  //   "scope.userInfo": true,
				  //   "scope.userLocation": true
				  // }
				}
			})
			let scene = wx.getLaunchOptionsSync()
			// setTimeout(()=>{
			// 	uni.showToast({
			// 		title:String(scene.scene),
			// 		icon:'none',
			// 		duration:5000
			// 	})
			// },1000)
			
			console.log('小程序场景',scene,scene.scene);
		},
		watch: {
			deviceList: {
				immediate: true,
				handler(value) {
					console.log('value=======',value);
				}
			}
		},
		methods: {
			onLoadHandler(options) {
				this.getDeviceListByPage(options);
			},
			// 分页查询设备列表
			getDeviceListByPage(options) {
				const data = {
					userGroupId: options.currentGroupId,
					page: 1,
					limit: 999
				};
				this.deviceList = []
				getApp().globalData.api.getDeviceListByPage(data, (result) => {
					console.log('分页查询设备列表:', result);
					let tempList = []
					this.getSharedDeviceList((sharedDeviceList)=>{
						tempList = [...result.data,...sharedDeviceList]
						
						tempList.forEach((item) => {
							if (!item.deviceNo.includes('vir')) {
								this.deviceList.push(item)
							}
						})
						let sns = [];
						this.deviceList.forEach((item) => {
							sns.push(item.deviceNo);
						});
						this.getSubscribeStatus(sns)
						if (sns.length > 0) {
							this.getDeviceToken(sns);
						}
					})
					
					// this.deviceList = result.data
				});
			},
			// 查询别人分享给当前用户的设备列表（当前用户已接收）
			getSharedDeviceList(callback){
				let data = {
					page:1,
					limit:999,
				}
				getApp().globalData.api.getSharedDeviceList(data, (result) => {
					callback(result.data)
				})
			},
			// 获取设备token
			getDeviceToken(sns) {
				const data = {
					sns: sns
				};
				getApp().globalData.api.getDeviceToken(data, (result) => {
					console.log('获取设备token:', result);
					this.deviceList.forEach((item) => {
						result.forEach((pro) => {
							if (item.deviceNo === pro.sn) {
								this.$set(item,'token',pro.token)
								// this.$set(item,'isSubscribe',uni.getStorageSync(item.deviceNo)?uni.getStorageSync(item.deviceNo).isSubscribe:false)
							}
						});
					});
					console.log('设备列表', this.deviceList);
				});
			},
			switchChange(item, e) {
				console.log('开关=====',e, item);
				this.disabled = true
				if(!item.isSubscribe){
					//取消订阅
					uni.showModal({
						title:'提示',
						content:'确定取消订阅吗？',
						success: (res) => {
							this.disabled = false
							if(res.confirm){
								this.cancelSubscribeMsgNoticeServe(item)
							}else{
								// uni.setStorageSync(item.deviceNo, {
								// 	isSubscribe: true
								// })
								this.deviceList.forEach((pro) => {
									if (item.deviceNo === pro.deviceNo) {
										pro.isSubscribe = true
									}
								});
							}
						}
					})
				}else{
					// 登录---获取票据--订阅消息
					// wx.login({
					// 	success: (res) => {
					// 		if (res.code) {
					// 			this.getDeviceTicket(item,res.code)
					// 		} else {
					// 			console.log('登录失败！' + res.errMsg)
					// 		}
					// 	}
					// })
					this.subscribeMsgNoticeServe(item)
				}
				// uni.setStorageSync(item.deviceNo, { isSubscribe:e })
				console.log('value', item, e);
			},
			//获取设备的订阅状态
			getSubscribeStatus(sns){
				let data = { sns:sns }
				getApp().globalData.api.getDeviceSubscribeStatus(data,(result)=>{
					console.log('订阅状态',result);
					this.deviceList.forEach((item)=>{
						result.forEach((item2)=>{
							if(item.deviceNo == item2.sn){
								this.$set(item,'isSubscribe',item2.subscribed)
							}
						})
					})
				
				})
			},
			// 获取票据---改为获取是否授权
			getDeviceTicket(item,code){
				let data = {
					code: code,
					sn: item.deviceNo
				}
				getApp().globalData.api.getDeviceAuth(data, (result) => {
					console.log('获取票据', result);
					this.isAuth = result.authed
					if(!result.authed){
						// uni.setStorageSync(item.deviceNo, {
						// 	isSubscribe: false
						// })
						this.deviceList.forEach((pro) => {
							if (item.deviceNo === pro.deviceNo) {
								pro.isSubscribe = false
							}
						});
						uni.showModal({
							title: '提示',
							content: '请搜索“小峰管家”微信公众号关注并开通消息提醒才会收到设备推送消息哦！',
							confirmText: '确定',
							showCancel:false,
							success: (res) => {
								this.disabled = false
								if (res.confirm) {
									// wx.navigateToMiniProgram({
									// 	appId:'wx6cdfb5bdf078af86'
									// })
								}
							}
						})
					}else{
						this.subscribeMsgNoticeServe(item)
					}
					// uni.showModal({
					// 	title: '提示',
					// 	content: '为了更快的获取设备的状态，服务号需要您的同意向您发送消息',
					// 	confirmText: '同意',
					// 	cancelText: '拒绝',
					// 	success: (res) => {
					// 		if (res.confirm) {
					// 			//调用订阅
					// 			// this.wxSubscribeMsg(item, result)
					// 			this.subscribeMsgNoticeServe(item)
					// 		} else if (res.cancel) {
					// 			uni.setStorageSync(item.deviceNo, {
					// 				isSubscribe: false
					// 			})
					// 			this.deviceList.forEach((pro) => {
					// 				if (item.deviceNo === pro.deviceNo) {
					// 					pro.isSubscribe = false
					// 				}
					// 			});
					// 			console.log('ddddddddddddd===',this.deviceList);
					// 		}
					// 	}
					// })
				});
			},
			//订阅微信消息
			wxSubscribeMsg(item, result) {
				wx.requestSubscribeDeviceMessage({
					tmplIds: [result.templateId],
					sn: item.deviceNo,
					snTicket: result.snTicket,
					modelId: result.modelId,
					success: (res) => {
						console.log('订阅成功', res)
						this.subscribeMsgNoticeServe(item)
					},
					fail(res) {
						console.log('订阅失败', res)
					}
				})
			},
			// 订阅消息（服务端）
			subscribeMsgNoticeServe(item) {
				let data = {
					sn: item.deviceNo,
					token: item.token,
				}
				getApp().globalData.api.subscribePMSMessage(data, (result) => {
					console.log('PMS订阅', result);
					this.disabled = false
					uni.showToast({
						title:'订阅成功',
						icon:'none'
					})
				});
			},
			//取消订阅
			cancelSubscribeMsgNoticeServe(item){
				let data = {
					sn: item.deviceNo,
					token: item.token,
				}
				getApp().globalData.api.cancelSubscribeMessage(data, (result) => {
					console.log('取消订阅', result);
					this.disabled = false
					uni.showToast({
						title:'取消订阅成功',
						icon:'none'
					})
				});
			},
			//复制公众号
			copyText(){
				uni.setClipboardData({
					data: '小峰管家',
					success:()=>{
						uni.showToast({
							title:'复制成功',
							icon:'none'
						})
					}
				});
			}
			
		}
	};
</script>
<style>
	.tips{
		margin-top: 90rpx;
		padding: 20rpx;
		font-size: 24rpx;
		color: #999;
	}
	.form {
		background: white;
		padding: 60rpx;
		border-radius: 10rpx;
	}

	.form .form-item {
		margin-top: 20rpx;
	}

	.form .form-title {
		text-align: center;
		margin-bottom: 40rpx;
		font-weight: bold;
	}

	.form .form-item .form-control {
		background: #efefef;
	}
</style>
